package org.marsdonne.audits;

import com.fasterxml.jackson.databind.JsonNode;
import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.TypeDef;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import java.util.Date;

/**
 * 用户（业务）操作（审计）域
 * 用于追溯用户级的业务功能操作情况
 */
@Entity
@Getter
@Setter
@EntityListeners(AuditingEntityListener.class)
@NoArgsConstructor
@TypeDef(typeClass = JsonBinaryType.class, defaultForType = JsonNode.class)
public class Operation extends LoggedEntity {
    @Column(nullable = false)
    private String operator;

    @Column(nullable = false)
    private String endpoint; //接入端，如app/小程序/h5pc等等

    @Column(nullable = false)
    private String function; //用户功能

    @Column(nullable = false)
    private String command;  //操作指令

    @Column(columnDefinition = "jsonb")
    private JsonNode arguments; //操作参数

    /**
     * 发起审计的服务标识
     */
    @Column(nullable = false)
    private String serviceId;

    public Operation(String operator, Date dateOperated, String endpoint, String function, String command, JsonNode arguments, String serviceId) {
        this.operator = operator;
        this.dateLogged = dateOperated;
        this.endpoint = endpoint;
        this.function = function;
        this.command = command;
        this.arguments = arguments;
        this.serviceId = serviceId;
    }

    public Operation(Operated operated) {
        this(operated.getOperator(), operated.getDateOperated(), operated.getEndpoint(), operated.getFunction(), operated.getCommand(), operated.getArguments(), operated.getServiceId());
    }
}
